package meta

import (
	"github.com/micro-plat/lib4go/db"
	"github.com/micro-plat/lib4go/types"
)

// GetMetaTableByID 根据ID获取元表信息
func getMetaTableByID(db db.IDBExecuter, tenantID int, tableID int64) (types.IXMap, error) {
	params := map[string]interface{}{
		"tenant_id": tenantID,
		"table_id":  tableID,
	}
	rows, err := db.Query(sqlGetTablesAndColumns, params)
	if err != nil {
		return nil, err
	}
	result := colums2TableColumns(rows)
	return result.Get(0), nil
}
func metaTableExists(db db.IDBExecuter, tenantID int, name string) (bool, error) {
	params := map[string]interface{}{
		"tenant_id": tenantID,
		"name":      name,
	}
	rows, err := db.Scalar(existMetaTable, params)
	if err != nil {
		return false, err
	}
	return types.GetInt(rows, 0) > 0, nil
}

func colums2TableColumns(rows types.XMaps, oldColumnName ...string) types.XMaps {
	// 循环处理查询结果
	cacheTable := make(map[int64]types.XMap)
	result := make(types.XMaps, 0)
	for _, row := range rows {
		tableID := row.GetInt64("table_id")
		// 检查缓存中是否存在当前表
		if _, ok := cacheTable[tableID]; !ok {
			tableMap := types.XMap{
				"table_id":    tableID,
				"title":       row.GetString("table_title"),
				"name":        row.GetString("table_name"),
				"description": row.GetString("table_description"),
				"columns":     make([]types.XMap, 0),
			}
			cacheTable[tableID] = tableMap
			result = append(result, tableMap)
		}
		columns := cacheTable[tableID]["columns"].([]types.XMap)

		// 添加当前列到表的列列表中
		columns = append(columns, types.XMap{
			"column_id":         row.GetInt64("column_id"),
			"title":             row.GetString("title"),
			"name":              row.GetString("name"),
			"type":              row.GetString("type"),
			"source":            row.GetString("source"),
			"method":            row.GetString("method"),
			"param":             row.GetString("param"),
			"is_prefab":         row.GetBool("is_prefab"),
			"description":       row.GetString("description"),
			"is_nullable":       row.GetBool("is_nullable"),
			"is_auto_increment": row.GetBool("is_auto_increment"),
			"default_value":     row.GetString("default_value"),
			"is_pk":             row.GetBool("is_pk"),
			"is_fk":             row.GetBool("is_fk"),
			"fk_column_id":      row.GetInt64("fk_column_id"),
			"is_dict_value":     row.GetBool("is_dict_value"),
			"is_dict_label":     row.GetBool("is_dict_label"),
			"is_like_query":     row.GetBool("is_like_query"),
			"is_dict_group":     row.GetBool("is_dict_group"),
			"old_name": types.DecodeString(len(rows), 1,
				types.GetStringByIndex(oldColumnName, 0),
				row.GetString("name")),
		})
		cacheTable[tableID]["columns"] = columns
	}
	return result
}
